#include <iostream>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

// 回调函数，用于处理HTTP响应数据
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if (curl) {
        // 设置目标URL
        std::string url = "https://api.deepseek.com/v1/chat/completions";
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);

        // 设置请求头
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "Authorization: Bearer sk-3b506807539e45769c5cc15b4e405606");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 构造请求体
        json requestBody = {
            {"model", "deepseek-chat"},
            {"messages", json::array({
                {
                    {"role", "system"},
                    {"content", "You are a helpful assistant"}
                },
                {
                    {"role", "user"},
                    {"content", "Please help me write a simple factory routine in cpp"}
                }
            })},
            {"stream", false}
        };

        // 将JSON转换为字符串
        std::string jsonStr = requestBody.dump();

        // 设置请求体数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonStr.c_str());

        // 设置回调函数和缓冲区
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        // 执行HTTP请求
        res = curl_easy_perform(curl);

        // 检查是否有错误发生
        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        } else {
            // 解析JSON响应
            try {
                json response = json::parse(readBuffer);
                std::cout << response["choices"][0]["message"]["content"] << std::endl;
            } catch (const json::parse_error& e) {
                std::cerr << "JSON parse error: " << e.what() << std::endl;
            }
        }

        // 清理资源
        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }

    curl_global_cleanup();
    return 0;
}